#include <iostream>
#include <queue>

using namespace std;

class Solution {
public:
    int maxDistance(vector<vector<int>>& grid) {
        queue<tuple<int, int>> queue;
        int height = grid.size();
        int width = grid[0].size();
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                if (grid[i][j]) {
                    queue.push({i, j});
                }
            }
        }
        int ans = 0;
        if (queue.size() == width * height || queue.size() == 0) {
            return -1;
        }
        while (queue.size() > 0) {
            for (int len = queue.size() - 1; len >= 0; len--) {
                tuple<int, int> pos = queue.front();
                queue.pop();
                int& i = get<0>(pos);
                int& j = get<1>(pos);
                if (i > 0 && !grid[i - 1][j]) {
                    grid[i - 1][j] = 1;
                    queue.push({i - 1, j});
                }
                if (i < height - 1 && !grid[i + 1][j]) {
                    grid[i + 1][j] = 1;
                    queue.push({i + 1, j});
                }
                if (j > 0 && !grid[i][j - 1]) {
                    grid[i][j - 1] = 1;
                    queue.push({i, j - 1});
                }
                if (j < width - 1 && !grid[i][j + 1]) {
                    grid[i][j + 1] = 1;
                    queue.push({i, j + 1});
                }
            }
            ans++;
        }
        return ans - 1;
    }
};